<template>
  <div class="order-data-item">
    <div class="row" v-if="state.orderData.type != 2">
      <div class="type" style="display: flex">
        <div>{{ platformObj[order.bc_type]?.name || order.bc_type }}</div>
        <div v-if="order.directionorder" style="font-weight: bold;">-反向单</div>

      </div>
      <app-flex style="margin-bottom: 4px; align-items: center">
        <span class="club">{{ oddskeych.result2 }}</span>
        <span class="club" v-if="oddskeych.afterColon != ''">:</span>
        <el-input v-model="order.pk_ratio" style="width: 60px; height: 24px; margin: 0 4px" />
        <!-- <span class="club" style="color: #ae8328">{{ order.pk_ratio }}</span> -->
        <!-- <span style="color: #ae8328">{{ item.odd }}</span> -->
        <span style="margin: 0 4px; font-size: 14px; font-weight: bold" v-if="state.orderData.type == 0">@</span>
        <!-- <span style="color: #f83e3e" v-if="state.orderData.type == 0">{{ order.odd }}</span> -->
        <el-input v-model="order.min_odd" style="width: 60px; height: 24px; margin-left: 4px" @focus="changeminodd" />
        <!-- <div class="range_input">
          <input type="text" v-model="order.min_odd" placeholder="最低" />
          <span>-</span>
          <input type="text" v-model="order.max_odd" placeholder="最高" />
        </div> -->

        <template v-if="order.reservation == 1">
          <span style="margin: 0 4px; font-size: 14px; font-weight: bold">@</span>
          <span style="color: #f83e3e">{{ order.min_odd }} - {{ order.max_odd }}</span>
        </template>
      </app-flex>
    </div>
    <div class="row" v-if="order.directionorder" style="margin-bottom: 8px">
      <div class="account">
        <el-select v-model="order.user_config_id" placeholder="用户分组" @change="changeuserconfig">
          <el-option v-for="item in state.users" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
    </div>
    <div class="row" :style="getvalue()">

      <div class="account" v-if="state.orderData.type != 2">
        <el-select v-model="order.userId" placeholder="选择账号" @focus="focususerId" @change="handleUserChange">
          <el-option v-for="item in users" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
      <div class="account" v-if="state.orderData.type == 2">
        <el-select v-model="order.bc_type" placeholder="选择平台" disabled class="he28"
          style="width: 116px; height: 28px; margin-bottom: 8px">
          <el-option v-for="(value, key) in platformObj" :key="key" :label="value.name" :value="key" />
        </el-select>
      </div>

      <template v-if="state.orderData.type == 0">
        <span class="label">总金额：</span>
        <el-input v-model="order.reservation_stake" class="orderpriceinput" style="width: 88px" type="number" />
      </template>
      <template v-if="state.orderData.type == 1">
        <template v-if="order.reservation_stake_type == 'max'">总金额：最大限额</template>
        <template v-else-if="order.reservation_stake_type == 'min'">总金额：最小限额 </template>
        <template v-else-if="order.stake">
          总金额：{{ order.stake }}
          <!-- <span class="label" style="margin-right: 8px"></span> -->
          <!-- <el-input v-model="order.stake" style="width: 88px; margin-right: 8px" type="number" /> -->
        </template>
      </template>
      <template v-if="state.orderData.type == 2">
        <span class="label" style="margin-bottom: 8px">总金额：</span>
        <el-input v-model="order.stake" class="orderpriceinput" style="width: 88px; height: 28px; margin-bottom: 8px"
          type="number" />
      </template>
      <template v-if="state.orderData.type == 2">
        <span class="label" style="margin-bottom: 8px">赔率：</span>
        <el-input v-model="order.odd" class="orderpriceinput" style="width: 88px; height: 28px; margin-bottom: 8px"
          type="number" />
      </template>

      <span v-if="order.max_stake">（{{ order.min_stake }}-{{ order.max_stake }}）</span>
    </div>
    <div class="row" style="margin-top: 8px">
      <div class="account">
        <!-- @change="store.changeOrdermode(order)" -->
        <el-select v-model="order.order_mode" @change="store.changeOrdermode(order)" placeholder="订单模式">
          <el-option label="单账号" value="one_user" />
          <el-option label="多账号" value="all_user" />
        </el-select>
      </div>
      <div class="account">
        <el-select v-model="order.place_mode" placeholder="下单模式">
          <el-option label="依次下单" :value="0" />
          <el-option v-if="order.order_mode == 'all_user' && !order.directionValue && !order.directionorder"
            label="同时下单" :value="1" />
          <el-option
            v-if="state.orderData.match.sport_type == 'basketball' && order.order_mode == 'all_user' && !order.directionValue && !order.directionorder"
            label="循环下单" :value="2" />
        </el-select>
      </div>
      <div class="account">
        <el-select v-model="order.runtime" placeholder="超时">
          <el-option v-for="item in overtimeList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
    </div>
    <div class="row" style="margin-top: 8px; display: flex; align-items: flex-start">
      <div class="account" v-if="order.order_mode == 'all_user'">
        <el-select v-model="order.user_id_list" multiple :max-collapse-tags="1" collapse-tags placeholder="选择账号"
          @focus="focususerId2" @change="handleUserChange">
          <el-option v-for="item in users" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </div>
      <div class="account" v-if="order.order_mode == 'all_user' && (order.place_mode == 1 || order.place_mode == 2)">
        <el-select v-model="order.money_mode" placeholder="金额分配">
          <el-option label="平均分配" value="average" />
          <el-option label="最高限额" value="max" />
        </el-select>
      </div>
      <div class="account" v-if="order.place_mode == '0'">
        <el-input-number v-model="order.order_second" placeholder="间隔时间" :controls="false" style="width: 115px">
          <template #suffix>
            <div class="el-input__icon">秒</div>
          </template>
        </el-input-number>
      </div>
    </div>

    <div class="subscribe" @click="handleSubscribe" v-if="state.orderData.type == 1">
      <template v-if="order.checked">
        <div class="subscribe-button subscribe-button__detail" v-if="order.reservation == 1"
          @click="store.showSubscribe(order)">
          查看预约
        </div>
        <div class="subscribe-button" v-else @click="store.showSubscribe(order)">预约</div>
      </template>
      <template v-else>
        <div class="subscribe-button subscribe-button__disabled">预约</div>
      </template>
    </div>
    <div class="checkbox" v-if="!order.directionorder">
      <el-checkbox v-model="order.checked" />
    </div>

    <div class="direction" v-if="order.isdirection">
      <div style="margin-right: 8px">反向：</div>
      <el-switch v-model="order.directionValue" @change="changedirectionswitch()" />
    </div>
  </div>
</template>
<script setup>
import { getPlatformUser, getMoneyLimit } from '@/api/user'
import { http } from '@/utils/http'
import { checkRoles } from '@/stores/roles'
const { state, store } = inject('Sell')
const { platformObj } = inject('/board')
const props = defineProps({
  order: Object,
})
const emits = defineEmits()
const oddIntervalId = ref(null)

const isIntervalId = ref(false)

const directionswitch = ref(false)

// 切换账号，重置选中用户
watch(
  () => state.userId,
  () => {
    props.order.userId = null
  }
)

const overtimeList = ref([
  {
    value: -1,
    label: '持续打单',
  },
  {
    value: -2,
    label: '关盘停止',
  },
  {
    value: -3,
    label: '赛前',
  },
  {
    value: -4,
    label: '赛中',
  },
  {
    value: -5,
    label: '赛前+赛中',
  },
  {
    value: 5,
    label: '5s停止',
  },
  {
    value: 10,
    label: '10s停止',
  },
  {
    value: 20,
    label: '20s停止',
  },
  {
    value: 30,
    label: '30s停止',
  },
  {
    value: 60,
    label: '1min停止',
  },
  {
    value: 120,
    label: '2min停止',
  },
  {
    value: 300,
    label: '5min停止',
  },
  {
    value: 600,
    label: '10min停止',
  },
  {
    value: 900,
    label: '15min停止',
  },
  {
    value: 1200,
    label: '20min停止',
  },
  {
    value: 2400,
    label: '30min停止',
  },
])

const users = computed(() => {
  const arr = []
  console.log(props.order.bc_type);
  const { orderData, userId } = state
  const { match } = orderData
  if (!props.order.directionorder) {
    if (state.platformUsers && state.platformUsers[props.order.bc_type] != null && state.platformUsers[props.order.bc_type] != undefined) {
      state.platformUsers[props.order.bc_type].forEach(item => {
        let label = item.user_name
        let a = {
          ...item,
          label: label,
          value: item.user_value.id,
        }
        if (isEmptyObject(item.user_value.place_league)) {
          arr.push(a)
        } else {
          if (item.user_value.place_league[match.league_id]) {
            arr.push(a)
          }
        }
        // arr.push({
        //   ...item,
        //   label: label,
        //   value: item.user_value.id,
        // })
      })

      if (arr.length > 0 && props.order.userId == undefined) {
        props.order.userId = arr[0].user_value.id
        getRealtimeOdd()
      }
    }
  } else {
    if (props.order.users_group && props.order.users_group[props.order.bc_type] != null && props.order.users_group[props.order.bc_type] != undefined) {
      props.order.users_group[props.order.bc_type].forEach(item => {
        let label = item.user_name
        let a = {
          ...item,
          label: label,
          value: item.user_value.id,
        }
        if (isEmptyObject(item.user_value.place_league)) {
          arr.push(a)
        } else {
          if (item.user_value.place_league[match.league_id]) {
            arr.push(a)
          }
        }

        // arr.push({
        //   ...item,
        //   label: label,
        //   value: item.user_value.id,
        // })
      })

      if (arr.length > 0 && props.order.userId == undefined) {
        props.order.userId = arr[0].user_value.id
        getRealtimeOdd()
      }
    }
  }

  console.log(arr);

  return arr
})

function isEmptyObject(obj) {
  return Object.keys(obj).length === 0 && obj.constructor === Object;
}

const oddskeych = computed(() => {
  let pk_odds_key = props.order.pk_odds_key
  let betweenColons = pk_odds_key.split(':')
  let targetChars = ['R', 'M', 'OU']
  const indices = betweenColons.reduce((acc, currentElement, index) => {
    if (targetChars.includes(currentElement)) {
      acc.push(index)
    }

    return acc
  }, [])
  let result = extractContentByColonIndex(props.order.pk_odds_key_ch, indices[0] + 1)
  let result2 = result.beforeColon.replace(/-?\d+/g, '')
  props.order.oddskey = result
  result.result2 = result2
  console.log(result)

  return result
})

const extractContentByColonIndex = (str, colonIndex) => {
  // 找到指定冒号的位置
  let colonCount = 0
  let colonPosition = -1

  for (let i = 0; i < str.length; i++) {
    if (str[i] === ':') {
      colonCount++
      if (colonCount === colonIndex) {
        colonPosition = i
        break
      }
    }
  }

  if (colonPosition !== -1) {
    // 截取指定冒号之前的内容
    const beforeColon = str.substring(0, colonPosition).trim()

    // 截取指定冒号之后的内容
    const afterColon = str.substring(colonPosition + 1).trim()

    return { beforeColon, afterColon }
  } else {
    return { beforeColon: str, afterColon: '' } // 或者可以抛出错误或者其他提示
  }
}

// 选择用户，获取用户对应金额限制
const handleUserChange = () => {
  const { order } = props

  order.user = users.value.find(item => item.value == order.userId)

  store.getOrderInfo(order)
}

const focususerId = () => {
  state.activecheckuserOrder = props.order
  if (props.order.userId == 'all') {
    state.checkuserAll = true
    state.radiouser = ''
  } else {
    state.checkuserAll = false
    state.radiouser = props.order.userId
  }
  state.userdialogshow.type = 'radio'
  state.userdialogshow.show = true
}
const focususerId2 = () => {
  state.activecheckuserOrder = props.order
  if (!props.order.user_id_list) {
    state.checkuserAll = true
    state.radiouser = []
  } else {
    state.checkuserAll = false
    state.radiouser = props.order.user_id_list
  }
  state.userdialogshow.type = 'checked'
  state.userdialogshow.show = true
}

const getvalue = () => {
  const userData = localStorage.getItem('kiteorderData');
  console.log(userData);
  
  if (userData && userData != 'undefined') {
    const userObj = JSON.parse(userData);

    if (props.order.runtime == undefined || props.order.runtime == null) {
      props.order.runtime = userObj.runtime
      // props.order.reservation_stake = userObj.reservation_stake
    }

    // props.orderdata.place_data[props.orderindex].order_mode = userData.order_mode
    // props.orderdata.place_data[props.orderindex].place_mode = userObj.place_mode
    // props.orderdata.place_data[props.orderindex].money_mode = userObj.money_mode

  }
}

const getRealtimeOdd = () => {
  const { orderData, userId } = state
  const { match } = orderData

  let body = {
    member_id: props.order.userId,
    user_type: 'member',
    nav_data: props.order.nav_data,
    pk_odds_key: props.order.pk_odds_key,
    user_config_id: userId,
    bc_type: match.bc_type
  }
  clearInterval(oddIntervalId.value)
  if (props.order.userId) {
    getMoneyLimit(body).then((res) => {

      clearInterval(oddIntervalId.value)
      if (isIntervalId.value && res.data.odd) {
        props.order.min_odd = (res.data.odd - 1).toFixed(2)
        props.order.max_stake = res.data.max_stake
        props.order.min_stake = res.data.min_stake
        oddIntervalId.value = setInterval(() => getRealtimeOdd(), 5000)
      } else {
        clearInterval(oddIntervalId.value)
      }


    }).catch(() => {

    })
  }


}

const changeminodd = () => {
  isIntervalId.value = false
}

const changedirectionswitch = () => {
  if (props.order.directionValue) {
    const { orderData, userId } = state
    const { match } = orderData
    http
      .post(`/match/other_platform_odd_list`, {
        bc_type: match.bc_type,
        event_type: match.event_type,
        league_id: match.league_id,
        home_id: match.home_id,
        away_id: match.away_id,
        pk_odds_key: props.order.reverse_pk_odds_key,
        nav_data: props.order.reverse_nav_data,
        odd: 0,
        sport_type: match.sport_type
      })
      .then(res => {

        store.selectDirectionMatch(res.data, props.order)
        props.order.place_mode = 0

      })
  } else {
    state.orderData.list[props.order.pk_odds_key] = state.orderData.list[props.order.pk_odds_key].filter(item => item.pk_odds_key !== props.order.reverse_pk_odds_key);
  }

}

const changeuserconfig = () => {
  getPlatformUser({ id: props.order.user_config_id }).then(res => {
    props.order.users_group = res.data
    getRealtimeOdd()
  })
}

const getuseShortcut = (row) => {
  const { orderData, userId } = state
  const { match } = orderData
  console.log(match);


  if (props.order.bc_type == row.bc_type && match.sport_type == row.sport) {
    console.log(props.order);
    console.log(row);

    state.userId = row.userId
    let userstr = ''
    if (row.user == '') {
      userstr = row.user_id_list[0]
    } else {
      userstr = row.user
    }
    props.order.userId = userstr

    store.onChangeUser()
    // handleUserChange()
    setTimeout(() => {
      props.order.userId = userstr
    }, 100);

    props.order.checked = true
    props.order.reservation_stake = row.stake

    changeminodd()
    props.order.order_mode = row.order_mode
    props.order.place_mode = row.place_mode
    props.order.runtime = row.runtime
    props.order.money_mode = row.money_mode
    props.order.order_second = row.order_second
    props.order.user_id_list = row.user_id_list
    setTimeout(() => {
      // emits('changeShortcut')
      getorderlimit(row.points)
    }, 100);


  }

}

const getorderlimit = (points) => {
  const { order } = props
  order.user = users.value.find(item => item.value == order.userId)
  let body = {
    member_id: order.userId,
    user_type: 'member',
    nav_data: order.nav_data,
    pk_odds_key: order.pk_odds_key,
  }
  if (order.userId) {
    getMoneyLimit(body)
      .then(res => {
        order.max_stake = res.data.max_stake
        order.min_stake = res.data.min_stake
        order.min_odd = (res.data.odd - points - 1).toFixed(2)
        console.log(order.min_odd);

        // order.min_odd = order.min_odd.toFixed(2)
        emits('changeShortcut')
      })
      .catch(() => {
        order.max_stake = null
        order.min_stake = null
      })
  }

}

onMounted(() => {
  clearInterval(oddIntervalId.value)
  // getRealtimeOdd()
  isIntervalId.value = true

  window.electron.useShortcut((event, msg) => {
    getuseShortcut(msg)
  })

})
onUnmounted(() => {
  isIntervalId.value = false
  clearInterval(oddIntervalId.value)
})
</script>
<style lang="scss" scoped>
.order-data-item {
  padding-left: 30px;
  margin-bottom: 8px;
  position: relative;
}

.row {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.type {
  color: #282828;
  width: 116px;
  margin-right: 16px;
}

.account {
  width: 116px;
  margin-right: 16px;
}

.club {
  color: #282828;
  font-weight: 600;
}

.label {
  // color: #778090;
  margin-left: 8px;
  font-family: PingFangSC;
  font-size: 14px;
  color: #778090;
}

.subscribe {
  position: absolute;
  right: 0;
  top: 50%;
  margin-top: -16px;
  text-align: center;
}

.subscribe-button {
  width: 60px;
  line-height: 32px;
  text-align: center;
  border-radius: 4px;
  background-color: var(--primary);
  color: #fff;
  cursor: pointer;
}

.subscribe-button__disabled {
  opacity: 0.3;
  // 禁用
  cursor: not-allowed;
}

.subscribe-button__detail {
  background: none;
  color: var(--primary);
}

.checkbox {
  position: absolute;
  top: -3px;
  left: 0;
}

::v-deep .account .el-select__selected-item {
  font-size: 12px;
}

::v-deep .orderpriceinput .el-input__inner {
  font-size: 14px;
  font-weight: bold;
  color: #252a30;
}

::v-deep .he28 .el-select__wrapper {
  min-height: 28px;
}

.range_input {
  width: 115px;
  height: 24px;
  display: inline-flex;
  align-items: center;
  padding: 0;
  justify-content: space-around;
  // background-color: #f3f5fd;
  border-radius: 0;
  cursor: text;
  transition: box-shadow 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  transform: translateZ(0);
  box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset;

  input {
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    border: none;
    outline: none;
    display: inline-block;
    height: 28px;
    line-height: 28px;
    margin: 0;
    padding: 0 4px 0 6px;
    width: 39%;
    text-align: left;
    font-size: 12px;
    color: #333;
    background-color: transparent;
  }
}

.direction {
  display: flex;
  align-items: center;
}
</style>

<style>
.range_input input::placeholder {
  font-family: PingFangSC;
  font-size: 12px;
  line-height: 1.43;
  color: #b7bdc6;
}

.order-data-item .el-input-number .el-input__inner,
.order-data-item .el-input-number .el-input__icon {
  font-size: 12px;
}
</style>
